#!/bin/bash
# 北交所录入助审系统 - Docker镜像构建和导出脚本
# 用于构建Docker镜像并导出为tar包供离线部署

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 配置变量
IMAGE_NAME="bjs-luruzhushen"
IMAGE_TAG="latest"
EXPORT_DIR="./docker-export"
EXPORT_FILE="${EXPORT_DIR}/${IMAGE_NAME}-${IMAGE_TAG}.tar"

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}北交所录入助审系统 - Docker构建和导出${NC}"
echo -e "${GREEN}========================================${NC}"

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo -e "${RED}错误: Docker未安装，请先安装Docker${NC}"
    exit 1
fi

# 检查Docker服务是否运行
if ! docker info &> /dev/null; then
    echo -e "${RED}错误: Docker服务未运行，请启动Docker${NC}"
    exit 1
fi

# 创建导出目录
mkdir -p "${EXPORT_DIR}"

# 步骤1: 构建Docker镜像
echo -e "\n${YELLOW}[步骤 1/3] 构建Docker镜像...${NC}"
docker build -t "${IMAGE_NAME}:${IMAGE_TAG}" .

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Docker镜像构建成功${NC}"
else
    echo -e "${RED}✗ Docker镜像构建失败${NC}"
    exit 1
fi

# 步骤2: 导出Docker镜像
echo -e "\n${YELLOW}[步骤 2/3] 导出Docker镜像到文件...${NC}"
docker save -o "${EXPORT_FILE}" "${IMAGE_NAME}:${IMAGE_TAG}"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Docker镜像导出成功${NC}"
else
    echo -e "${RED}✗ Docker镜像导出失败${NC}"
    exit 1
fi

# 步骤3: 压缩导出文件
echo -e "\n${YELLOW}[步骤 3/3] 压缩导出文件...${NC}"
cd "${EXPORT_DIR}"
tar -czf "${IMAGE_NAME}-${IMAGE_TAG}.tar.gz" "${IMAGE_NAME}-${IMAGE_TAG}.tar"

if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ 压缩完成${NC}"
    rm "${IMAGE_NAME}-${IMAGE_TAG}.tar"
else
    echo -e "${YELLOW}⚠ 压缩失败，但tar文件已生成${NC}"
fi

cd ..

# 显示结果
echo -e "\n${GREEN}========================================${NC}"
echo -e "${GREEN}构建和导出完成！${NC}"
echo -e "${GREEN}========================================${NC}"

# 显示镜像信息
echo -e "\n${YELLOW}镜像信息:${NC}"
docker images "${IMAGE_NAME}:${IMAGE_TAG}"

# 显示导出文件信息
echo -e "\n${YELLOW}导出文件:${NC}"
if [ -f "${EXPORT_DIR}/${IMAGE_NAME}-${IMAGE_TAG}.tar.gz" ]; then
    FILE_SIZE=$(du -h "${EXPORT_DIR}/${IMAGE_NAME}-${IMAGE_TAG}.tar.gz" | cut -f1)
    echo -e "  文件: ${EXPORT_DIR}/${IMAGE_NAME}-${IMAGE_TAG}.tar.gz"
    echo -e "  大小: ${FILE_SIZE}"
else
    FILE_SIZE=$(du -h "${EXPORT_FILE}" | cut -f1)
    echo -e "  文件: ${EXPORT_FILE}"
    echo -e "  大小: ${FILE_SIZE}"
fi

# 显示部署说明
echo -e "\n${YELLOW}离线部署步骤:${NC}"
echo -e "1. 将导出文件传输到目标服务器"
echo -e "2. 在目标服务器上运行: docker load -i ${IMAGE_NAME}-${IMAGE_TAG}.tar.gz"
echo -e "   或: tar -xzf ${IMAGE_NAME}-${IMAGE_TAG}.tar.gz && docker load -i ${IMAGE_NAME}-${IMAGE_TAG}.tar"
echo -e "3. 运行容器: docker run -d -p 8580:8580 --name bjs-luruzhushen ${IMAGE_NAME}:${IMAGE_TAG}"
echo -e "   或使用docker-compose: docker-compose up -d"

echo -e "\n${GREEN}全部完成！✨${NC}"

